<?php

namespace app\middleware;

use Closure;
use think\Config;
use think\Request;
use think\Response;

/**
 * 自定义跨域请求处理中间件
 */
class CrossDomain
{
    protected $cookieDomain;

    protected $header = [
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Max-Age'           => 1800,
        'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers'     => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With',
    ];

    public function __construct(Config $config)
    {
        $this->cookieDomain = $config->get('cookie.domain', '');
    }

    /**
     * 处理跨域请求
     * @access public
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        // 如果是OPTIONS预检请求，直接返回204状态码
        if ($request->isOptions()) {
            $origin = $request->header('origin', '*');

            $header = $this->header;
            if (!isset($header['Access-Control-Allow-Origin'])) {
                if ($origin && ('' == $this->cookieDomain || str_contains($origin, $this->cookieDomain))) {
                    $header['Access-Control-Allow-Origin'] = $origin;
                } else {
                    $header['Access-Control-Allow-Origin'] = '*';
                }
            }

            return response('', 204, $header);
        }

        // 获取原始响应
        $response = $next($request);

        // 添加跨域头信息
        $origin = $request->header('origin', '*');
        $header = $this->header;

        if (!isset($header['Access-Control-Allow-Origin'])) {
            if ($origin && ('' == $this->cookieDomain || str_contains($origin, $this->cookieDomain))) {
                $header['Access-Control-Allow-Origin'] = $origin;
            } else {
                $header['Access-Control-Allow-Origin'] = '*';
            }
        }

        return $response->header($header);
    }
}
